package _17_graph;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author: mornd
 * @dateTime: 2023/6/24 - 20:21
 * 图的广度优先搜索 Breadth-first search
 */
public class BFS {
    public static void main(String[] args) {
        // 构建顶点
        Vertex v1 = new Vertex("1");
        Vertex v2 = new Vertex("2");
        Vertex v3 = new Vertex("3");
        Vertex v4 = new Vertex("4");
        Vertex v5 = new Vertex("5");
        Vertex v6 = new Vertex("6");

        // 建立边的关系
        v1.edges = List.of(new Edge(v3, 9),
                new Edge(v2, 7),
                new Edge(v6, 14));

        v2.edges = List.of(new Edge(v4, 15));

        v3.edges = List.of(new Edge(v4, 11),
                new Edge(v6, 2));

        v4.edges = List.of(new Edge(v5, 6));

        v6.edges = List.of(new Edge(v5, 9));
        v5.edges = List.of();

        // 1 3 2 6 4 5
        bfs(v1);
    }

    private static void bfs(Vertex v) {
        Queue<Vertex> queue = new LinkedList<>();
        queue.offer(v);
        v.visited = true;
        while (!queue.isEmpty()) {
            Vertex poll = queue.poll();
            System.out.println(poll.name);
            for (Edge edge : poll.edges) {
                if (!edge.linked.visited) {
                    edge.linked.visited = true;
                    queue.offer(edge.linked);
                }
            }
        }
    }
}
